<?php
ini_set('default_charset', 'utf-8');
header('Content-Type: text/html; charset=UTF-8');
class DataBase {

	private $conexion;
	private $resource;
	private $sql;
	public static $queries;
	private static $_singleton;

	public static function getInstance(){
		if (is_null (self::$_singleton)) {
			self::$_singleton = new DataBase();
		}
		return self::$_singleton;
	}

	private function __construct(){
		$myFile = get_include_path()."/libraries/php.conf";
		$fh = fopen($myFile, 'r');
		$theData = fread($fh, filesize($myFile));
		fclose($fh);
		$arr_data = split(",",$theData);
		$this->conexion = mysql_connect('localhost',$arr_data[0] ,$arr_data[1]);
		mysql_select_db( $arr_data[2] , $this->conexion );

		$this->queries = 0;
		$this->resource = null;


		mysql_query("SET NAMES UTF8" , $this->conexion);

	}

	public function has_rows(){
		return @mysql_num_rows($this->resource)>0;
	}
	public function num_rows(){
		return @mysql_num_rows($this->resource);
	}
	public function execute($sql){
		$this->sql = str_replace("'null'","''", $sql);
		//mysql_set_charset('utf8',$this->conexion); 
		if( ! ( $this->resource = mysql_query( $this->sql , $this->conexion ) ) ){
			echo mysql_errno($this->conexion) . ": " . mysql_error($this->conexion) . "<br>";
			echo $sql.'<br><br>';

			return null;
		}
		return $this->resource;
	}

	public function alter(){
		if( ! ( $this->resource = mysql_query( $this->sql , $this->conexion ) ) ){
			return false;
		}
		return true;
	}

	public function loadObjectList($list = NULL){
		if ( ! ( $cur = $this->execute($this->sql) ) ){
			return null;
		}
		if($list != NULL){
			$array = $list;
		}else{
			$array = array();	
		}
		while (($row = @mysql_fetch_object( $cur ))){
/*			foreach ($row as $key => $value){
				$row->$key = utf8_encode($value);
			}*/

			$array[] = $row;
		}
		return $array;
	}

	public function setQuery( $sql ){
		if( empty( $sql ) ){
			return false;
		}
		$this->sql = $sql;
		return true;
	}

	public function freeResults(){
		@mysql_free_result( $this->resource );
		return true;
	}
	public function last_inserted_id(){
		return mysql_insert_id($this->conexion );
	}
	public function loadObject(){
		if (($cur = $this->execute())){
			if (($object = mysql_fetch_object( $cur ))){
				@mysql_free_result( $cur );
				return $object;
			}else {
				return null;
			}
		}
		else {
			return false;
		}
	}

	function __destruct(){
		@mysql_free_result( $this->resource );
		@mysql_close( $this->conexion );
	}
}
?>